<!--语义识别结果播报弹框-->
<template>
  <div :class="'discern-container ' + ($Ctl.isCs(true) ? 'no-margin' : '')">
    <img class="audio-tip" v-if="isAudioPlay" src="../../assets/images/audio/audio-play.gif" />
    <img class="audio-tip" v-else src="../../assets/images/audio/audio-discern.gif" />
    <div class="audio-text">
      <p v-if="!realTimeDiscernOpen" class="audio-text-loop">
        {{ audioText }}
      </p>
      <p v-else class="audio-text-loop-slow">
        {{ currentAudioText }}
        <span v-if="
                        audioText == defualtWords || audioText == cmdExcuteWords
                    " class="load"></span>
      </p>
      <!-- 
          <p v-if="audioText==defualtWords" >{{audioText}}<span class="load"></span></p>
          <p v-else  class="audio-text-loop">{{audioText}}</p> -->
    </div>
    <audio ref="myAudio" :src="currentAudioUrl" autoplay="" controls="" @error="playAudioError()" :paused="audioPaused" :muted="muted" @ended="playAudioEnd()" style="display:none;"></audio>
  </div>
</template>

<script>
import IatTaste from "@/libs/audio/audioDiscern.js";
// import {matchTopCmd} from '@/libs/audio/keysCore.js'
import PROCESSOR from "@/libs/audio/newKeyScript.js";
import TTSRecorder from "@/libs/audio/onlineTts.js";
require("@/libs/audio/enc-base64-min.js");

var iatTaste;
var ttsRecorder = new TTSRecorder();

export default {
  name: "AudioDiscern",
  components: {},
  props: {
    openAudioDispcernHome: {
      type: Function,
      default() {
        false;
      },
    },
  },
  data() {
    return {
      realTimeDiscernOpen: false, //开启实时识别（常态）
      defualtWords: "您好，请问有什么可以帮您的？", //默认识别提示！
      defualtFailWords: "抱歉，没有听明白您的意思，换个方式说呗！", //默认未识别到结果提示！
      cmdExcuteWords: "找到以上相近的结果，请问您要执行哪一条？", //默认识别提示！
      isAudioPlay: true, //是否是播放语音
      currentAudioUrl: "", //当前播放音频url
      audioPaused: false, //是否暂停
      audioText: "您好，请问有什么可以帮您的？", //语音文本
      currentAudioText: "", // 当前播报的语音文本
      muted:false
    };
  },
  created() {
    this.isShow = false;
    this.loopAudios = []; // 需要继续播放的音频
    this.discernList = []; // 识别结果集合
    this.audioIsPlaying = false; //是否在播放音频
    this.eventIdOfHideFrm = 0; //延迟30秒自动隐藏弹层
    window.FunList.openPushAudio = this.openPushAudio; //打开推送语音模块
    window.FunList.openAudioDiscern = this.openAudioDiscern; //（打开/关闭）语义识别模块页面,开始语义识别
    window.FunList.setDiscernResult = this.setDiscernResult; //设置识别结果
    window.FunList.excuteDiscernResult = this.excuteDiscernResult; //识别周期结束，执行识别结果
    window.FunList.closeDiscern = this.closeDiscern; //关闭识别功能
  },
  mounted() {
    let that = this;
    that.initPage(); //初始化语义识别页面
    ttsRecorder.onWillStatusChange = function (oldStatus, status) {
      // 可以在这里进行页面中一些交互逻辑处理：按钮交互等
      // let btnState = {
      //     init: '立即合成',
      //     ttsing: '正在合成',
      //     play: '停止播放',
      //     endPlay: '重新播放',
      //     errorTTS: '合成失败',
      // }
      // console.log('oldStatus：'+ oldStatus + '; status:' + status)
      if (status == "play") {
        that.currentAudioText = that.audioText;
      } else if (oldStatus == "play" && status == "endPlay") {
        if (iatTaste) {
          // 开启语音识别
          iatTaste.start();
        }
      }
    };
  },
  methods: {
    // 页面初始化
    initPage() {
      let that = this;
      that.isShow = false;
      that.currentAudioText = "";
      that.audioText = "您好，请问有什么可以帮您的？";
      that.realTimeDiscernOpen = false;
      that.currentAudioUrl = "";
      this.audioActive = false;
      that.audioPaused = false;
      that.audioIsPlaying = false;
      that.loopAudios = [];
    },
    // 打开推送语音页面
    openPushAudio(audioUrl, tips, muted=false) {
      let that = this;
      //正在人工识别状态下，不做语音播报
      if (!that.realTimeDiscernOpen /* && audioUrl */ && tips) {
        clearTimeout(that.eventIdOfHideFrm);
        that.isShow = true;
        // 控制父级弹框
        if (
          that.openAudioDispcernHome &&
          typeof that.openAudioDispcernHome === "function"
        ) {
          that.openAudioDispcernHome(that.isShow);
        }
        that.isAudioPlay = true;
        that.audio_play(audioUrl, tips, muted);
      }
    },
    // 播放音频结束事件
    playAudioEnd() {
      console.log("playAudioEnd");
      this.audioIsPlaying = false;
      // src为空会触发error事件
      this.currentAudioUrl = "";
    },
    // 播放失败
    playAudioError() {
      console.log("playAudioEmptyOrError");
      this.audioIsPlaying = false;
      this.loop_play();
    },
    // 播放音频
    audio_play(audioUrl, tips, muted) {
      let that = this;
      // 若是当前还在播放，则加到队列里去
      if (that.audioIsPlaying) {
        if (that.loopAudios.length < 1000) {
          that.loopAudios.push({ audioUrl: audioUrl, tips: tips, muted });
        }
      } else {
        that.audioText = tips;
        if (audioUrl) {
          that.currentAudioUrl = audioUrl;
          that.audioIsPlaying = true;
          this.$nextTick(()=>{
            this.muted=muted
            this.$refs.myAudio.muted=muted
          })
        }
      }
    },
    // 停止播放
    audio_stop() {
      this.loopAudios = [];
      this.audioPaused = true;
      this.isAudioPlay = false;
    },
    // 循环播放
    loop_play() {
      let that = this;
      if (that.loopAudios.length > 0) {
        //获取第一个视频，并移除第一个视频
        var audio = that.loopAudios.shift();
        that.audio_play(audio.audioUrl, audio.tips, audio.muted);
      } else {
        this.closeAudioPop()
      }
    },
    closeAudioPop(){
      //延迟30秒自动隐藏弹层
      clearTimeout(this.eventIdOfHideFrm);
      this.eventIdOfHideFrm = setTimeout( ()=> {
        this.isShow = false;
        // 控制父级弹框
        if (
          this.openAudioDispcernHome &&
          typeof this.openAudioDispcernHome === "function"
        ) {
          this.openAudioDispcernHome(this.isShow);
          this.$Cs.closeDetailsPage(10107);
        }
      }, 30000);
    },
    // （打开/关闭）语义识别模块页面,开始语义识别,若为1标识语意指令关闭
    openAudioDiscern(isClose) {
      let that = this;
      if (that.isShow) {
        clearTimeout(that.eventIdOfHideFrm);
        if ((isClose && isClose == 1) || !that.isAudioPlay) {
          that.initPage();
          //语意指令关闭
          //或已打开，且是在语义识别阶段，关闭语义识别页面
          that.isShow = false;
          // 控制父级弹框
          if (
            that.openAudioDispcernHome &&
            typeof that.openAudioDispcernHome === "function"
          ) {
            that.openAudioDispcernHome(that.isShow);
          }
          //关闭自动识别
          that.realTimeDiscernCtl(false);
        } else {
          //已打开，且是在播放音频阶段，切换至语义识别模块
          clearTimeout(that.eventIdOfHideFrm);
          that.audio_stop();
          that.isAudioPlay = false;
          //开始自动识别
          that.realTimeDiscernCtl(true);
        }
      } else {
        that.isShow = true;
        // 控制父级弹框
        if (
          that.openAudioDispcernHome &&
          typeof that.openAudioDispcernHome === "function"
        ) {
          that.openAudioDispcernHome(that.isShow);
        }
        that.isAudioPlay = false;
        that.audio_stop();
        //开始自动识别
        that.realTimeDiscernCtl(true);
      }
    },
    // 开始识别
    audio_discern_start() {
      let that = this;
      iatTaste = null;
      iatTaste = new IatTaste();
      // iatTaste.init();
      // 消防助手语音播报
      // that.audioText=that.defualtWords;
      that.setAudioText(that.defualtWords);
    },
    // 设置识别结果
    setDiscernResult(str) {
      let that = this;
      // 展示用户说的话
      that.currentAudioText = str;
      console.log("过程数据：" + str);
      // 重说指令
      if (
        str.indexOf("重说") > -1 ||
        str.indexOf("说错了") > -1 ||
        str.indexOf("再来一遍") > -1
      ) {
        // 关闭识别结果集合弹框
        that.$Ctl.closeAudioDisposeCtl();
        that.setAudioText("好的，您请说");
      }
    },
    // 周期识别结束，开始执行识别结果
    excuteDiscernResult(data) {
      console.log("最终结果：" + data);
      let that = this;
      let tipStr = "";
      if (data && data.length > 0) {
        // 去除特殊字符
        let text = data.replace(/[&\|\\\*,，。 ^%$#@\-]/g, "");
        let _index = false;
        // 当前展示了识别相近结果窗口时，先判断说的词中是否有执行顺序的序号，若有执行识别命令词展示中的结果，若没有再执行词库匹配
        if (that.discernList.length > 0) {
          if (text.indexOf("1") >= 0 || text.indexOf("一") >= 0) {
            _index = 1;
          } else if (text.indexOf("2") >= 0 || text.indexOf("二") >= 0) {
            _index = 2;
          } else if (text.indexOf("3") >= 0 || text.indexOf("三") >= 0) {
            _index = 3;
          } else {
            _index = false;
          }
        }

        // 匹配到结果，直接执行
        if (_index && _index > 0) {
          tipStr = that.discernList[_index - 1]?that.discernList[_index - 1].result:'';
          // 执行识别结果集合中的指令
          that.$Ctl.excuteAudioCmdCtl(
            JSON.stringify(that.discernList[_index - 1])
          );
          // 关闭识别结果集合弹框
          that.$Ctl.closeAudioDisposeCtl();
          that.discernList = [];
        } else {
          // 智能匹配结果，实现排序展示
          // 自定义识别大类、小类，进行智能搜索
          let relt = PROCESSOR.start(text);
          // let rslt=matchTopCmd(6, that.audioText);
          // 识别结果大于80%直接执行
          if (relt.length > 0) {
            if (relt[0].score > 80) {
              that.discernList = [];
              tipStr = relt[0].result;
              //执行结果
              that.$Ctl.excuteAudioCmdCtl(JSON.stringify(relt[0]));
              // 关闭识别结果集合弹框
              that.$Ctl.closeAudioDisposeCtl();
            } else {
              // 更新识别结果集合
              that.discernList = relt;
              // 打开语义识别处理页面，进行命令词展示处理
              that.$Ctl.setAudioDisposeCtl(relt);
              //默认词改为，请选择序号执行命令
              tipStr = that.cmdExcuteWords;
            }
          } else {
            tipStr = that.defualtFailWords;
          }
        }
      } else {
        tipStr = that.defualtWords;
      }
      // 设置提示语
      that.setAudioText(tipStr);
    },
    // 开启/关闭实时识别（常态）
    realTimeDiscernCtl(isOpen) {
      let that = this;
      if (isOpen) {
        this.disTimer = 9;
        // that.audioText=that.defualtWords;
        // that.setAudioText(that.defualtWords);
        that.realTimeDiscernOpen = true;
        that.audio_discern_start();
      } else {
        iatTaste.close();
        iatTaste = null;
        that.realTimeDiscernOpen = false;
        that.$Cs.closeDetailsPage(10107);
      }
    },
    //关闭识别功能
    closeDiscern() {
      if (iatTaste) {
        iatTaste.close();
        iatTaste = null;
        this.initPage();
      }
    },
    // 消防助手回应信息语音播报
    helpBotVoiceTts(text) {
      if (text) {
        ttsRecorder.setParams({
          voiceName: "xiaoyan",
          tte: "UTF8",
          text: text,
        });
        ttsRecorder.start();
      }
    },
    setAudioText(text) {
      // 停止语音识别
      iatTaste && iatTaste.stop();
      this.helpBotVoiceTts(text);
      this.audioText = text;
    },
  },
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.discern-container {
  //background:  url("../img/audio-bg.gif")  no-repeat;
  &.no-margin {
    margin-top: -19px;
  }
  overflow: hidden;
}
.audio-tip {
  width: 45px;
  height: 45px;
  float: left;
}
.audio-text {
  display: inline-block;
  font-size: 26px;
  font-family: PingFang SC;
  font-weight: 500;
  color: rgba(2, 221, 241, 1);
  line-height: 40px;
  overflow: hidden;
}

/*文字过多轮播*/
.audio-text-loop {
  display: inline-block;
  white-space: nowrap;
  animation: 7s wordsLoop linear infinite normal;
}
.audio-text-loop-slow {
  display: inline-block;
  white-space: nowrap;
  animation: 12s wordsLoop linear infinite normal;
}
@keyframes wordsLoop {
  0% {
    transform: translateX(200px);
    -webkit-transform: translateX(200px);
  }
  100% {
    transform: translateX(-100%);
    -webkit-transform: translateX(-100%);
  }
}

@-webkit-keyframes wordsLoop {
  0% {
    transform: translateX(200px);
    -webkit-transform: translateX(200px);
  }
  100% {
    transform: translateX(-100%);
    -webkit-transform: translateX(-100%);
  }
}
.mainApp{
  /* 设置了浏览器宽度不大于2000px时样式调整 */
  @media screen and (max-width: 2000px) {
    .discern-container {
      width: 900px;
      height: 100px;
      background: url(../../assets/images/audio/audio-bg-1920.gif) center 15px
        no-repeat;
    }
    .audio-tip {
      margin-left: 232px;
      margin-top: 44px;
    }
    .audio-text {
      width: 370px;
      margin-top: 46px;
    }
  }
  /* 设置了浏览器宽度不小于2000px时样式调整 */
  @media screen and (min-width: 2000px) {
    .discern-container {
      left: 600px;
      width: 2100px;
      // height: 200px;
      background: url(../../assets/images/audio/audio-bg-3840.gif) center 15px
        no-repeat;
    }
    .audio-tip {
      margin-left: 700px;
      margin-top: 44px;
    }
    .audio-text {
      width: 640px;
      margin-top: 46px;
    }
  }
}

.load {
  height: 4px;
  width: 4px;
  display: inline-block;
  animation: change 1.3s infinite steps(1, start);
}
@keyframes change {
  25% {
    box-shadow: 4px 0 0 rgba(2, 221, 241, 1);
  }
  50% {
    box-shadow: 4px 0 0 rgba(2, 221, 241, 1), 17px 0 0 rgba(2, 221, 241, 1);
  }
  75% {
    box-shadow: 4px 0 0 rgba(2, 221, 241, 1), 17px 0 0 rgba(2, 221, 241, 1),
      32px 0 0 rgba(2, 221, 241, 1);
  }
}
</style>
